package cn.action;

import cn.base.BaseAction;
import cn.domain.*;
import cn.utils.HQLHelper;
import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.ServletActionContext;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.task.Task;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import sun.misc.BASE64Encoder;

import javax.mail.Session;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2017/4/26.
 */
@Controller
@Scope("prototype")
public class FlowAction extends BaseAction<Application> {
    private Long id;
    private File resource;//文件上传
    private Long formTemplateId = 0L;
    private Long applicationId;//属性驱动
    private InputStream inputStream;//用于文件下载
    private String fileName;//文件名
    private String taskId;//办理任务的Id，待我审批中审批处理
    private String comment;//获取审批处理页面中的审批意见
    private Boolean submitBoolean;//接受前台数据，用于判断前台点击的是同意还是不同意

    public Boolean getSubmitBoolean() {
        return submitBoolean;
    }

    public void setSubmitBoolean(Boolean submitBoolean) {
        this.submitBoolean = submitBoolean;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    public Long getApplicationId() {
        return applicationId;
    }

    public void setApplicationId(Long applicationId) {
        this.applicationId = applicationId;
    }

    public InputStream getInputStream(){
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName){
        this.fileName = fileName;
    }

    public FlowAction(){
        model.setStatus("");
    }
    public Long getFormTemplateId() {
        return formTemplateId;
    }

    public void setFormTemplateId(Long formTemplateId) {
        this.formTemplateId = formTemplateId;
    }

    public File getResource() {
        return resource;
    }

    public void setResource(File resource) {
        this.resource = resource;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    /**
     * 跳转模板查询页面
     *
     * @return
     */
    public String templatelist() {
        List<Template> list = templateService.findAll();
        getValueStack().set("list", list);
        return "list";
    }

    /**
     * 跳转提交申请页面
     *
     * @return
     */
    public String addUI() {
        Template template = templateService.getById(model.getId());
        getValueStack().push(template);
        return "add";
    }

    /**
     * 添加，提交申请
     *
     * @return
     */
    public String add() {
        //处理上传文件
        String path = upFile(resource);
        //保存申请记录
        Application application = new Application();
        User user = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
        application.setFilePath(path);      //设置文件路径
        String title = null;
        Template template = templateService.getById(model.getId());
        title = title + template.getName() + "_" + user.getName() + "_" + new Date();
        application.setTitle(title);     //设置申请标题
        application.setTemplate(template);          //使用的模板
        application.setApplyTime(new Date());     //设置申请时间
        application.setApplicant(user);         //设置申请人
        application.setStatus(Application.STATUS_RUNNING);            //申请的状态
        flowService.save(application);
        //启动流程实例
        return "toMyApplicationList";
    }

    public String myApplicationList() {
        //查询分页数据----我的申请HQLHelper
        HQLHelper hqlHelper = new HQLHelper(Application.class);
        User user = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
        hqlHelper.addWhere(" applicant=? ", user);
        if (formTemplateId != 0) {
            //根据Id查询模版
            Template template = templateService.getById(formTemplateId);
            hqlHelper.addWhere(" template=? ", template);
        }
        if(model.getStatus().equals("1")){
            hqlHelper.addWhere(" status =?","审批中");
        }else if(model.getStatus().equals("2")){
            hqlHelper.addWhere(" status = ? ","未通过");
        }else if(model.getStatus().equals("3")){
            hqlHelper.addWhere(" status = ?","已通过");
        }
        // 执行查询
        PageBean pageBean = flowService.getPageBean(hqlHelper, getCurrentPage());
        getValueStack().set("list", pageBean.getRecordList());
        getValueStack().push(pageBean);
        List<Template> templates=templateService.findAll();
        getValueStack().set("template",templates);
        return "myApplicationList";
    }

    /**
     * 下载
     * @return
     * public String downLoad() throws IOException {
    //根据id查询数据
    Template template=templateService.getById(model.getId());
    //查询需要下载的输入流
    downLoad=templateService.getInputStreamById(model.getId());
    //文件名
    fileName=template.getName()+".doc";
    String  agent=ServletActionContext.getRequest().getHeader("user-agent");
    fileName=encodeDownloadFilename(fileName,agent);
    return "downLoad";
    }
     */
    public String downLoad() throws IOException {
        inputStream=flowService.getInputStreamById(applicationId);
        Application application=flowService.getById(applicationId);
        fileName=application.getTitle()+".doc";
        String header=ServletActionContext.getRequest().getHeader("user-agent");
        fileName=encodeDownloadFilename(fileName,header);
        return "downLoad";
    }

    /**
     * 下载文件时，针对不同浏览器，进行附件名的编码
     * @param filename 下载文件名
     * @param agent 客户端浏览器(通过request.getHeader("user-agent")获得)
     * @return 编码后的下载附件名
     * @throws IOException
     */
    public String encodeDownloadFilename(String filename, String agent) throws IOException {
        if(agent.contains("Firefox")){ // 火狐浏览器
            filename = "=?UTF-8?B?"+new BASE64Encoder().encode(filename.getBytes("utf-8"))+"?=";
        }else{ // IE及其他浏览器
            filename = URLEncoder.encode(filename,"utf-8");
        }
        return filename;
    }
    /**
     * 上传
     *
     * @param file
     * @return
     */
    public String upFile(File file) {
        String realPath = ServletActionContext.getServletContext().getRealPath("/WEB-INF");
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd");
        String dateStr = sdf.format(new Date());
        dateStr = realPath + dateStr;
        File dateFile = new File(dateStr);
        if (!dateFile.exists()) {
            dateFile.mkdirs();
        }
        String filepath = dateStr + UUID.randomUUID().toString() + ".doc";
        File dest = new File(filepath);
        file.renameTo(dest);
        return filepath;
    }
    /**
     * 查询流转记录
     */
    public String histApprovedList(){
        if(applicationId!=0){
            Application application=flowService.getById(applicationId);
            List<ApproveInfo> list=approveInfoService.findApproveInfoList(application);
            getValueStack().set("list",list);
            return "histApproved";
        }
        return null;
    }

    /**
     * 待我审批(我的任务列表)
     * @return
     */
    public String myTaskList(){
        User user= (User) ServletActionContext.getRequest().getSession().getAttribute("user");
        List<TaskView> list=flowService.findTaskList(user);
        getValueStack().set("list",list);
        return "myTaskList";
    }

    /**
     * 跳转到审批页面
     * @return
     */
    public String toTaskManage(){
        return  "toTask";
    }

    /**
     * 审批，并跳转至我的任务列表
     * @return
     */
    public String TaskManage(){
            Application application=flowService.getById(applicationId);//获取application
            User user= (User) ServletActionContext.getRequest().getSession().getAttribute("user");//获取当前用户
            //给ApproveInfo各项设置值并保存
            ApproveInfo approveInfo=new ApproveInfo();
            approveInfo.setApprover(user);
            approveInfo.setAproverTime(new Date());
            approveInfo.setApproval(submitBoolean);
            approveInfo.setComment(comment);
            approveInfo.setApplicaTion(application);
            approveInfoService.save(approveInfo);

            flowService.approve(approveInfo,taskId);
        return "toMyTaskList";
    }
    public void saveApproveInfo(){
    }
}
